﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AutoMapper;

namespace UserGroupData
{
    public class SponsorRepository : ISponsorRepository
    {
        public SponsorDTO GetSponsor(int id)
        {
            using (var ctx = new UserGroupEntities())
            {
                var meeting = ctx.Sponsors.Where(d => d.Id == id);
                var entity = meeting.FirstOrDefault();
                Mapper.CreateMap<Sponsor, SponsorDTO>();
                var dto = Mapper.Map<Sponsor, SponsorDTO>(entity);
                return dto;
            }
        }

        public List<SponsorDTO> GetAllSponsors()
        {
            using (var ctx = new UserGroupEntities())
            {
                var entities = ctx.Sponsors.ToList();
                Mapper.CreateMap<Sponsor, SponsorDTO>();
                var dto = Mapper.Map<List<Sponsor>, List<SponsorDTO>>(entities);
                return dto;
            }
        }

        public int AddNewSponsor(SponsorDTO dto)
        {
            using (var ctx = new UserGroupEntities())
            {
                Mapper.CreateMap<SponsorDTO, Sponsor>();
                var entity = Mapper.Map<SponsorDTO, Sponsor>(dto);
                ctx.AddToSponsors(entity);
                ctx.SaveChanges();
                return entity.Id;
            }
        }

        public void UpdateSponsor(SponsorDTO dto)
        {
            using (var ctx = new UserGroupEntities())
            {
                var entity = ctx.Sponsors.Single(d => d.Id == dto.Id);
                Mapper.CreateMap<SponsorDTO, Sponsor>();
                Mapper.Map(dto, entity);
                ctx.ApplyCurrentValues("Sponsors", entity);
                ctx.SaveChanges();
            }
        }

        public void DeleteSponsor(int id)
        {
            using (var ctx = new UserGroupEntities())
            {
                Sponsor dbDept = ctx.Sponsors.First(d => d.Id == id);
                ctx.DeleteObject(dbDept);
                ctx.SaveChanges();
            }
        }
    }
}
